package com.ncloud.aaaa.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.aaaa.model.Menu;
import com.ncloud.aaaa.model.Subsys;
import com.ncloud.aaaa.repository.MenuRepository;
import com.ncloud.aaaa.service.MenuService;
import com.ncloud.aaaa.service.SubsysService;
import com.ncloud.common.exception.UserException;

@Service
public class MenuServiceImpl implements MenuService {
	
	private static final Logger logger = LogManager.getLogger(MenuServiceImpl.class);
	@Autowired
	private MenuRepository repository;
	@Autowired
	private SubsysService subsysService;

	@Override
	public JSONArray getMenuList(JSONObject userObj) {
		if(!userObj.containsKey("userID")){
    		throw new UserException("1004", "缺少参数");
    	}
    	Long userId = userObj.getLong("userID");
		JSONArray sysArray = new JSONArray();
		//菜单不需要缓存，每次都需要最新数据
		//获取角色和子系统对应的菜单信息
		List<Subsys> subsysList = subsysService.getSubsysListByUserId(userId);
		for (Subsys subsys : subsysList) {
			JSONObject sjo = new JSONObject();
			sjo.put("text", subsys.getSysName());
			sjo.put("id", subsys.getId());
//			sjo.put("translate", subsys.getTranslate());
			sjo.put("icon", subsys.getIcon());
			List<Menu> menus = new ArrayList<Menu>();
			try{
				menus = repository.getMenusBySubsysAndUserId(userId,subsys.getId());
			}catch (Exception e) {
				throw new UserException(e.toString());
			}
			JSONArray menuArray = geneMenuConstruction(menus);
			sjo.put("menu", menuArray);
			sysArray.add(sjo);
		}
		return sysArray;
	}

	private JSONArray geneMenuConstruction(List<Menu> menus) {
		JSONArray menuArray = new JSONArray();
		for (Menu menu : menus) {
			JSONArray submenu= new JSONArray();
			JSONObject mjo = new JSONObject();
			mjo.put("id", menu.getId());
			mjo.put("text", menu.getName());
			mjo.put("link", menu.getHref());
			mjo.put("icon", menu.getIcon());
			mjo.put("isShow", menu.getIsShow());
//			mjo.put("translate", menu.getTranslate());
			mjo.put("submenu", submenu);
			if(!"0".equals(menu.getParentId())){
				for (Object object : menuArray) {
					JSONObject jo = (JSONObject)object;
					if(jo.get("id").toString().equals(menu.getParentId())){
						JSONArray mja = jo.getJSONArray("submenu");
						mja.add(mjo);
					}
				}
				continue;
			}
			
			menuArray.add(mjo);
		}
		return menuArray;
	}
}
